package com.zijing2333.adaptivescheduling.SwitcherManager;

import android.content.Context;

import com.zijing2333.servicerunner.JSStatus;
import com.zijing2333.servicerunner.TaskInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Switcher 类用于管理任务执行，设备 IP 获取以及与服务的连接。
 */
public class Switcher {

    private static final String TAG = Switcher.class.getSimpleName();

    private TaskRunnerConnectionManager taskRunnerConnectionManager;
//    private TaskStateStorageManager taskStateStorageManager;
    private TaskExecuteManager taskExecuteManager;

    /**
     * 构造方法，初始化任务执行管理器和连接管理器。
     *
     * @param context 上下文对象
     */
    public Switcher(Context context) {
        taskRunnerConnectionManager = new TaskRunnerConnectionManager(context);
//        taskStateStorageManager = new TaskStateStorageManager();
        taskExecuteManager = new TaskExecuteManager(taskRunnerConnectionManager);
    }

    /**
     * 分发 JS 任务。
     *
     * @param taskId   任务 ID
     * @param switchTaskInfo 任务信息
     */
    public boolean dispatchJsTask(int type,String taskId, SwitchTaskInfo switchTaskInfo) {
        return taskExecuteManager.dispatchJsTask(type,taskId, switchTaskInfo);
    }

    /**
     * 获取当前执行状态。
     *
     * @param serviceId 服务 ID
     * @return 当前执行状态
     */
    public String getCurrentExecutionState(String serviceId) {
        return taskExecuteManager.getCurrentExecutionState(serviceId);
    }

    /**
     * 恢复服务数据状态。
     *
     * @param serviceId 服务 ID
     */
    public void restoreServiceDataState(String serviceId,String data) {
        taskExecuteManager.restoreServiceDataState(serviceId,data);
    }

    public void deleteReplicaCode(String serviceId){
        taskExecuteManager.deleteReplicaCode(serviceId);
    }

    public Map<String, JSStatus> getJSServiceStatusMap(){
        return taskExecuteManager.getJSServiceStatusMap();
    }

    /**
     * 获取设备 IP。
     *
     * @param serviceId 服务 ID
     * @param callback  设备 IP 回调
     */
    public void getDeviceIP(String serviceId, DeviceIpCallback callback) {

        OkHttpClient httpClient = new OkHttpClient();
        String url = "http://url.com/device-ip?serviceId=" + serviceId;

        Request request = new Request.Builder()
                .url(url)
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse;
                    try {
                        jsonResponse = new JSONObject(responseBody);
                        String deviceIp = jsonResponse.optString("device_ip");
                        callback.onSuccess(deviceIp);
                    } catch (JSONException e) {
                        callback.onFailure(e);
                    }
                } else {
                    callback.onFailure(new IOException("Unexpected response code: " + response.code()));
                }
            }
        });
    }
    //该函数还没写好----------------6.3日
    //如果你要传很多字段，你最好就定义一个类，然后用fastjson转换成json字符串，然后我这边再用fastjson解析成对应的类
    public String getDeviceIP2(String serviceId,String sourceIp) {
        OkHttpClient httpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        JSONObject jsonObj = new JSONObject();
        try {
            jsonObj.put("serviceId",serviceId);
            jsonObj.put("sourceIp",sourceIp);
            String data = jsonObj.toString();
            String url ="http://switchService";
            RequestBody requestBody =RequestBody.create(mediaType,data);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            Response response = httpClient.newCall(request).execute();
            String responseBody = response.body().string();
            JSONObject jsonResponse = new JSONObject(responseBody);
            String deviceIp = jsonResponse.optString("IP");
            return deviceIp;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 停止 JS 执行。
     *
     * @param serviceId 服务 ID
     */
    public void stopJSExecution(String serviceId) {
        taskExecuteManager.stopJSExecution(serviceId);
    }

    /**
     * 断开与服务的连接。
     */
    public void disconnectFromService() {
        taskRunnerConnectionManager.disconnectFromService();
    }

    /**
     * 设备 IP 回调接口。
     */
    public interface DeviceIpCallback {
        void onSuccess(String deviceIp);

        void onFailure(Exception e);
    }
}